const { getAll, update, add, remove, getCount, getOne } = require('../utils/dbTools')
const tableName = 'orders'

/**
 * 获取订单列表 
 * @param {object} map 查询条件 
 */
const getOrderList = async (map = {}) => {
    const result = await getAll(tableName, map)
    return result
}

/**
 * 获取订单总数
 * @param {object} map 查询条件 
 */
const getOrderCount = async (map = {}) => {
    const result = await getCount(tableName, map)
    return result
}


/**
 * 获取订单详情
 * @param {object} map 查询条件 
 */
const getOrderInfo = async (map = {}) => {
    const result = await getOne(tableName, map)
    return result
}


/**
 * 订单删除 
 * @param {number} id 订单id
 */
const removeOrder = async (id) => {
    if (!id) return false
    const result = await remove(id, tableName)
    return result
}


/**
 * 提交认证订单 
 * @param {object} data 订单信息
 */
const addOrder = async (data) => {
    if (Object.keys(data).length === 0) return false
    const timeStamp = Date.now()
    // 随机生成订单id
    const orderNumber = `Auth${timeStamp}${Math.random().toString(16).slice(2, 5)}`
    data.out_trade_no = data.trade_no = orderNumber
    const result = await add(data,tableName)
    return result
}

/**
 * 更新订单状态 
 * @param {object} data 订单信息
 */
const updateOrder = async (data) => {
    const { id } = data
    if (!id) return false
    delete data.id
    const result = await update(id, data, tableName)
    return result
}

module.exports = {
    addOrder, updateOrder, getOrderList, removeOrder, getOrderCount, getOrderInfo
}
